package de.uni_mannheim.informatik.ai.dame_ai.main.ui;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import java.io.File;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import javax.imageio.ImageIO;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import de.uni_mannheim.informatik.ai.dame_ai.dame.ui.DameGuiFrame;
import de.uni_mannheim.informatik.ai.dame_ai.main.application.GameProperty;
import de.uni_mannheim.informatik.ai.dame_ai.main.application.GameSettings;
import de.uni_mannheim.informatik.ai.dame_ai.main.application.MainPlayer;
import de.uni_mannheim.informatik.ai.dame_ai.main.ui.MainMenuDictionary.Phrases;
import de.uni_mannheim.informatik.ai.dame_ai.util.FileSystem;
import de.uni_mannheim.informatik.ai.dame_ai.util.GameSettingsParser;
import de.uni_mannheim.informatik.ai.dame_ai.util.LoadGameDialog;
import de.uni_mannheim.informatik.ai.dame_ai.util.WindowClosingAdapter;


public class MainMenuFrame extends JFrame implements Observer, WindowStateListener, ComponentListener{
	
	/**
	 * @param args
	 */
	ObservablePanel currentPanel;
	GameProperty[] games;
	GameSettings gameSettings = new GameSettings();
	GameSettingsParser persistor = new GameSettingsParser();
	Cursor paperplane;

	public MainMenuFrame(){
		setSize(600, 450);
		initializeGames();
		this.addComponentListener(this);
		//setContentPane();
	}
	private void initializeGames(){
		
		try {
			paperplane = getToolkit().createCustomCursor
			(ImageIO.read(new File("media/main/cursor_paperplane.png")), new Point(2,0), "Cursor");
		} catch (HeadlessException e) {} catch (IndexOutOfBoundsException e) {} catch (IOException e) {}
		setCursor(paperplane);
		imagePath = new File("media" + File.separator + "main" + File.separator);
		games = new GameProperty[1];
		games[0] = new GameProperty(2, "dame", "Dame","Dame, ein tolles spiel",FileSystem.GameName.dame);
	}
	File imagePath;
	 private static void createAndShowGUI() {
		 MainMenuFrame mainMenu = new MainMenuFrame();
			mainMenu.addWindowListener(new WindowClosingAdapter(true));
			mainMenu.setBackground(Color.gray);
			mainMenu.startChooseGame();
			mainMenu.setVisible(true);
			Dimension screenSize = mainMenu.getToolkit().getScreenSize();
			int width=600, height=450;
			Dimension size = new Dimension(width, height);
			Point upperLeftCorner=new Point((screenSize.width-width)/2, (screenSize.height-height)/2);
			Rectangle bounds = new Rectangle(upperLeftCorner, size);
			mainMenu.setBounds(bounds);
			System.out.println(mainMenu.getBounds());
			
	 }
	public void redisplayMainMenu(){

		invalidate();
		startChooseGame();
		repaint();
		setVisible(true);
	}
	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });

		
	}
	boolean choosingGame = false;
	GameProperty currentGame;
	private void startChooseGame(){
		choosingGame = true;
		currentPanel = new GameChooserPanel(getWidth()-16,getHeight()-38, imagePath, games, gameSettings);
		((GameChooserPanel)currentPanel).setFrameReference(this);
		currentPanel.addObserver(this);
		getContentPane().add(currentPanel);
		System.out.println("Waiting for Game choice");
	}
	private void finishChooseGame(GameProperty currentGame){
		choosingGame = false;
		System.out.println("Received Game Choice");
		this.currentGame = currentGame;
		//currentPanel.observableObject.deleteObserver(this);
		getContentPane().remove(currentPanel);
		if(!currentGame.isQuickStart()){
			startChooseModus();
		} else {
			File quickLoad = FileSystem.getAutoSave(currentGame.getGame());
			if(quickLoad.exists()){
				gameSettings =persistor.getGameSettings(quickLoad);
				gameSettings.setLoadGame(false);
				gameSettings.setFinished(false);
				gameSettings.setReplay(false);
				gameSettings.setFilePath(null);
				currentGame.setQuickStart(false);
				startGame();
			}else {
				startChooseModus();
			}
		}
	}
	boolean choosingModus=false;
	String gameModus;
	private void startChooseModus(){
		choosingModus = true;
		currentPanel = new GameModusChooserPanel(getWidth()-16,getHeight()-38, imagePath,gameSettings);
		((GameModusChooserPanel)currentPanel).setFrameReference(this);
		currentPanel.addObserver(this);		
		getContentPane().add(currentPanel);
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
	           public void run() {
	        	currentPanel.invalidate();
	        	currentPanel.validate();
	        	currentPanel.repaint();
	           }
			}
		);
		
		//setVisible(true);
	}
	private void finishChooseModus(GameSettings modus){
		gameSettings = modus;
		modus.setPlayers(null);
		if(modus.isLoadGame() || modus.isReplay()){
			
			File destFile = null;
			if(currentGame.getName().equals("dame")){
				destFile=LoadGameDialog.askForFile(this, FileSystem.GameName.dame);
				
			}
			if(currentGame.getName().equals("menschaergeredichnicht")){
				destFile=LoadGameDialog.askForFile(this, FileSystem.GameName.mensch_aergere);
			}
			if(currentGame.getName().equals("mill")){
				destFile=LoadGameDialog.askForFile(this, FileSystem.GameName.mill);
			}
			if(currentGame.getName().equals("battleship")){
				destFile=LoadGameDialog.askForFile(this, FileSystem.GameName.battleship);
			}
			
			if(destFile  == null)return;
			gameSettings.setFilePath(destFile);
			GameSettings temp = persistor.getGameSettings(destFile);
			gameSettings.setPlayers(temp.getPlayers());
			
		}
		choosingModus = false;
		getContentPane().remove(currentPanel);
		if(!gameSettings.isReplay()){
			startChoosePlayers();
		} else {
			startGame();
		}
		
	}
	boolean choosingPlayers=false;
	private void startChoosePlayers(){
		choosingPlayers = true;
		currentPanel = new ChoosePlayerPanel(getWidth()-16,getHeight()-38,currentGame,imagePath,gameSettings);
		((ChoosePlayerPanel)currentPanel).setFrameReference(this);
		currentPanel.addObserver(this);		
		getContentPane().add(currentPanel);
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
	           public void run() {
	        	currentPanel.invalidate();
	        	currentPanel.validate();
	        	currentPanel.repaint();
	           }
			}
		);
	}
	
	private void finishChoosePlayers(Object result){
		MainPlayer[] players = (MainPlayer[])result;
		gameSettings.setPlayers(players);
		choosingPlayers=false;
		getContentPane().remove(currentPanel);
		startGame();
	}
	@Override
	public void update(Observable arg0, Object result) {
		if(choosingGame){
			if(result instanceof GameProperty){
				finishChooseGame((GameProperty)result);
			}
		}else if(choosingModus){
			if(result instanceof GameSettings){
				finishChooseModus((GameSettings)result);
			}
		} else if(choosingPlayers){
			finishChoosePlayers(result);
		}
		
	}
	Rectangle windowPos=this.getBounds();
	ChildWindowClosingAdapter adapter;
	private void startGame(){
		windowPos=this.getBounds();
		 adapter= new ChildWindowClosingAdapter();
		if(currentGame.getName().equals("dame")){
			javax.swing.SwingUtilities.invokeLater(new Runnable() {
	           public void run() {
	        	   DameGuiFrame.createAndShowGUI(gameSettings, windowPos, adapter);
	           }
			}
			);
			
			this.setVisible(false);
			
			
		}
		if(currentGame.getName().equals("menschaergeredichnicht")){
			
		}
		if(currentGame.getName().equals("mill")){
			
		}
		if(currentGame.getName().equals("battleship")){
			
		}
		//removeAll();
	}
	
	public void doOnReturnButtonClicked(String s) { // TODO
		if(s.equals("GameModusChooserPanel")){
			choosingModus = false;
			getContentPane().remove(currentPanel);
			startChooseGame();
		}
		if(s.equals("ChoosePlayerPanel")){
			choosingPlayers = false;
			getContentPane().remove(currentPanel);
			startChooseModus();
		}
		
	}
	@Override
	public void windowStateChanged(WindowEvent arg0) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
	           public void run() {
	        	currentPanel.calculateGeneralBounds();
	        	currentPanel.repaint();
	           }
			}
		);
		
	}
	@Override
	public void componentHidden(ComponentEvent arg0) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
	           public void run() {
	        	currentPanel.calculateGeneralBounds();
	        	currentPanel.repaint();
	           }
			}
		);
		
	}
	@Override
	public void componentMoved(ComponentEvent arg0) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
	           public void run() {
	        	currentPanel.calculateGeneralBounds();
	        	currentPanel.repaint();
	           }
			}
		);
		
	}
	@Override
	public void componentResized(ComponentEvent arg0) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
	           public void run() {
	        	currentPanel.calculateGeneralBounds();
	        	currentPanel.repaint();
	           }
			}
		);
		
	}
	@Override
	public void componentShown(ComponentEvent arg0) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
	           public void run() {
	        	currentPanel.calculateGeneralBounds();
	        	currentPanel.repaint();
	           }
			}
		);
		
	}
	private class ChildWindowClosingAdapter extends WindowAdapter{

		public ChildWindowClosingAdapter(){
			
		}
		@Override
		public void windowClosing(WindowEvent e) {
			System.out.println("ChildWindowClosingAdapter2");
			
			JFrame child =(JFrame)e.getComponent();
			//child.dispose();
			redisplayMainMenu();
			super.windowClosed(e);
			

			
		}
		@Override
		public void windowClosed(WindowEvent e) {
			System.out.println("ChildWindowClosingAdapter");
			
			JFrame child =(JFrame)e.getComponent();
			//child.dispose();
			redisplayMainMenu();
			super.windowClosed(e);
			
		}
	}
	
	public void changeLanguage(){
		String[] langStrings = {"English", "Deutsch"};
		JComboBox langList = new JComboBox(langStrings);
		Object[] message = {currentPanel.mainDict.translate(Phrases.main_language)+":", langList};
		Object[] options = {currentPanel.mainDict.translate(Phrases.main_ok), currentPanel.mainDict.translate(Phrases.main_cancel)};
		
		int choice = JOptionPane.showOptionDialog(this, message, currentPanel.mainDict.translate(Phrases.main_language), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
				null, options, currentPanel.mainDict.translate(Phrases.main_ok));
		if(choice == 0){
			gameSettings.setLanguage(langList.getSelectedIndex());
			if(choosingGame){
				choosingGame = false;
				getContentPane().remove(currentPanel);
				startChooseGame();
			}
			if(choosingModus){
				choosingModus = false;
				getContentPane().remove(currentPanel);
				startChooseModus();
			}
			if(choosingPlayers){
				choosingPlayers = false;
				getContentPane().remove(currentPanel);
				startChoosePlayers();
			}
		}
	}
}
